package zz.app.ustbgsmanager.activities;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TextInputEditText;
import android.support.design.widget.TextInputLayout;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.InputType;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.view.ContextThemeWrapper;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import zz.app.ustbgsmanager.utils.GSManager;
import zz.app.ustbgsmanager.R;
import zz.app.ustbgsmanager.utils.MetricsUtils;
import zz.app.ustbgsmanager.utils.NetworkUtils;

public class LoginActivity extends AppCompatActivity {
    GSManager manager;
    Context context;
    ImageView imgYzm;
    ImageView imgLook;
    TextInputEditText etUsername;
    TextInputEditText etPassword;
    TextInputEditText etPinyin;
    TextInputEditText etYzm;
    SharedPreferences loginSp;
    TextInputLayout tilUsername;
    TextInputLayout tilPinyin;
    TextInputLayout tilPassword;
    RelativeLayout rlChangeUser;
    RelativeLayout rlPassword;
    RelativeLayout rlMainLayout;
    LinearLayout llContainer;
    TextView tvCurrentUser;
    TextView tvNoNetHint;
    Button btnLogin;
    Button btnChangeUser;
    AlertDialog loginCheckDialog;
    BroadcastReceiver receiver;
    boolean bUsedUser;
    boolean bNoNetwork;
    Handler handler;

    private void gotoMainActivicty() {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                Intent intent = new Intent(context, MainActivity.class);
                ActivityOptionsCompat activityOptionsCompat =
                        ActivityOptionsCompat.makeCustomAnimation(context, R.anim.activity_in, R.anim.activity_out);
                startActivity(intent, activityOptionsCompat.toBundle());
                finish();
            }
        },250);

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        init();
    }

    @SuppressLint("ClickableViewAccessibility")
    private void init() {
        getWindow().setNavigationBarColor(getResources().getColor(R.color.navigationBarColor,null));
        context = this;
        llContainer = findViewById(R.id.llContainer);
        tvNoNetHint=findViewById(R.id.tvNoNetHint);
        if(NetworkUtils.isNetworkAvaliable(this)) {
            llContainer.setVisibility(View.VISIBLE);
            tvNoNetHint.setVisibility(View.GONE);
        }else{
            llContainer.setVisibility(View.GONE);
            tvNoNetHint.setVisibility(View.VISIBLE);
            if(loginCheckDialog!=null){
                loginCheckDialog.dismiss();
            }
        }
        tvCurrentUser = findViewById(R.id.tvCurrentUser);
        tilPassword = findViewById(R.id.tilPassword);
        tilUsername = findViewById(R.id.tilUsername);
        tilPinyin = findViewById(R.id.tilPinyin);
        rlChangeUser = findViewById(R.id.rlChangeUser);
        rlPassword = findViewById(R.id.rlPassword);
        etUsername = findViewById(R.id.etUsername);
        etPassword = findViewById(R.id.etPassword);
        etPinyin = findViewById(R.id.etPinyin);
        etYzm = findViewById(R.id.etYzm);
        imgYzm = findViewById(R.id.imgYzm);
        handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                switch (msg.what) {
                    case GSManager.INTENT_GET_YZM:
                        imgYzm.setImageBitmap(manager.getBmyzm());
                        btnLogin.setEnabled(true);
                        break;
                    case GSManager.INTENT_CHECK_ISLOGIN:
                        boolean b = (boolean) msg.obj;
                        if (b) {
                            Toast.makeText(context, "登录成功", Toast.LENGTH_SHORT).show();
                            gotoMainActivicty();//跳转MainActivity
                        } else {
                            initIfNotLogin();
                            llContainer.setVisibility(View.VISIBLE);
                            if (NetworkUtils.isNetworkAvaliable(context))
                                Snackbar.make(rlMainLayout, "请重新登录", Snackbar.LENGTH_SHORT).show();
                        }
                        if (loginCheckDialog != null) {
                            loginCheckDialog.dismiss();
                        }
                        break;
                    case GSManager.INTENT_LOGIN_SUCCESS:
                        Toast.makeText(context, "登录成功", Toast.LENGTH_SHORT).show();
                        boolean bUsed = loginSp.getBoolean("used", false);
                        if (!bUsed) {
                            loginSp.edit().putBoolean("used", true)
                                    .putString("username", etUsername.getText().toString())
                                    .putString("password", etPassword.getText().toString())
                                    .putString("pinyin", etPinyin.getText().toString())
                                    .apply();
                        }
                        gotoMainActivicty();// 跳转MainActivity
                        break;

                    case GSManager.INTENT_LOGIN_FAILED:
                        llContainer.setVisibility(View.VISIBLE);
                        Toast.makeText(context, "登录失败", Toast.LENGTH_SHORT).show();
                        manager.setManagerState(GSManager.STATE_WAIT);
                        manager.load(GSManager.LOGIN_URL);
                        break;
                    case GSManager.INTENT_NO_NETWORK:
                        if (loginCheckDialog != null) {
                            bNoNetwork = true;
                            llContainer.setVisibility(View.GONE);
                            loginCheckDialog.dismiss();
                            tvNoNetHint.setVisibility(View.VISIBLE);

                        }
                        break;
                }
                return true;
            }
        });
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        try {
            manager = GSManager.getInstance(context);
            manager.setHandler(handler);
        } catch (Exception e) {
            e.printStackTrace();
        }
        rlMainLayout = findViewById(R.id.main_layout);
        boolean bLogout = getIntent().getBooleanExtra("logout", false);
        if (!bLogout)
            checkLoginState();
        else
            initIfNotLogin();
        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
                if (cm != null) {
                    NetworkInfo info=cm.getActiveNetworkInfo();
                    if (info!=null&&info.isAvailable()) {
                        if (bNoNetwork) {
                            checkLoginState();
                            bNoNetwork = false;
                            tvNoNetHint.setVisibility(View.GONE);
                        }
                    }else{
                        bNoNetwork = true;
                        Snackbar.make(rlMainLayout,"请检查网络状态",Snackbar.LENGTH_SHORT).show();
                        llContainer.setVisibility(View.GONE);
                        tvNoNetHint.setVisibility(View.VISIBLE);
                        if(loginCheckDialog!=null){
                            loginCheckDialog.dismiss();
                        }
                    }
                }

            }
        };

        imgYzm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                manager.setManagerState(GSManager.STATE_WAIT);
                manager.load(GSManager.LOGIN_URL);
            }
        });
        imgLook = findViewById(R.id.imgLook);
        imgLook.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int t;
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        t = etPassword.getSelectionStart();
                        etPassword.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                        etPassword.setSelection(t);
                        break;
                    case MotionEvent.ACTION_UP:
                    case MotionEvent.ACTION_CANCEL:
                        t = etPassword.getSelectionStart();
                        etPassword.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD | InputType.TYPE_CLASS_TEXT);
                        etPassword.setSelection(t);
                        break;
                }
                etPassword.invalidate();
                return true;
            }
        });
        loginSp = getSharedPreferences("login", MODE_PRIVATE);
        bUsedUser = loginSp.getBoolean("used", false);
        if (!bUsedUser) {
            loginLayout(true, null);
        } else {
            loginLayout(false, loginSp.getString("username", ""));
        }
        btnChangeUser = findViewById(R.id.btnChangeUser);
        btnChangeUser.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loginSp.edit().putBoolean("used", false).apply();
                bUsedUser = false;
                loginLayout(true, null);
                etUsername.setText("");
                etPassword.setText("");
                etPinyin.setText("");
            }
        });
        btnLogin = findViewById(R.id.btnLogin);
        btnLogin.setOnClickListener(new View.OnClickListener() {
            String username;
            String password;
            String pinyin;
            String yzm;

            @Override
            public void onClick(View v) {
                if (!bUsedUser) {
                    username = etUsername.getText().toString();
                    password = etPassword.getText().toString();
                    pinyin = etPinyin.getText().toString();
                } else {
                    username = loginSp.getString("username", "");
                    password = loginSp.getString("password", "");
                    pinyin = loginSp.getString("pinyin", "");
                }
                yzm = etYzm.getText().toString();
                btnLogin.setEnabled(false);
                manager.tryLogin(username, password, pinyin, yzm);

            }
        });
        manager.setManagerState(GSManager.STATE_WAIT);
        manager.load(GSManager.LOGIN_URL);
        //manager.getWebView().loadUrl(GSManager.LOGIN_URL);
//        llContainer.addView(webView);
        IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(receiver, filter);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
    }


    private void initIfNotLogin() {
        manager.setManagerState(GSManager.STATE_WAIT);
        manager.load(GSManager.LOGIN_URL);
        etYzm.getText().clear();

    }

    private void checkLoginState() {
        AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(this, R.style.DialogTheme_LoginCheckDialogTheme));
        builder.setCancelable(false);
        builder.setView(R.layout.login_check_islogin);
        loginCheckDialog = builder.create();
        loginCheckDialog.setCanceledOnTouchOutside(false);
        loginCheckDialog.show();
        Window window = loginCheckDialog.getWindow();
        if (window != null) {
            window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            WindowManager.LayoutParams params=window.getAttributes();
            params.width= MetricsUtils.dp2px(context,320);
            window.setAttributes(params);
        }
        manager.setManagerState(GSManager.STATE_CHECKISLOGIN);
        manager.load(GSManager.DEFAULT_URL);


    }

    private void loginLayout(boolean b, String tmpUsername) {
        if (b) {
            rlChangeUser.setVisibility(View.GONE);
            tilUsername.setVisibility(View.VISIBLE);
            tilPinyin.setVisibility(View.VISIBLE);
            rlPassword.setVisibility(View.VISIBLE);
        } else {
            rlChangeUser.setVisibility(View.VISIBLE);
            tilUsername.setVisibility(View.GONE);
            tilPinyin.setVisibility(View.GONE);
            rlPassword.setVisibility(View.GONE);
            SpannableStringBuilder builder = new SpannableStringBuilder();
            builder.append("将使用");
            ForegroundColorSpan span = new ForegroundColorSpan(getResources().getColor(R.color.colorPrimary, null));
            SpannableString string = new SpannableString(tmpUsername);
            string.setSpan(span, 0, tmpUsername.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            builder.append(string);
            builder.append("账号登录");
            tvCurrentUser.setText(builder);
        }
    }

}
